/**
 * @Author: Vincent
 * @Description:
 * @File:  time
 * @Version: 1.0.0
 * @Date: 2022/3/27 14:18
 */

package timehandler

import (
	"github.com/pkg/errors"
	"time"
)

const FormatLayoutDate = "2006-01-02"
const FormatLayoutTime = "2006-01-02 15:04:05"

// NewTime accept time string like "2006-01-02" or "2006-01-02 15:04:05"
func NewTime(in string) (time.Time, error) {
	layout := ""
	if len(in) == len(FormatLayoutTime) {
		layout = FormatLayoutTime
	} else if len(in) == len(FormatLayoutDate) {
		layout = FormatLayoutDate
	} else {
		return time.Time{}, errors.Errorf("Check the time format:%s", in)
	}
	out, err := time.ParseInLocation(layout, in, time.Local)
	if err != nil {
		return time.Time{}, errors.WithStack(err)
	}
	return out, err
}

func GetTimeSubDay(bef, now time.Time) int {
	var day int
	swap := false
	if bef.Unix() > now.Unix() {
		bef, now = now, bef
		swap = true
	}

	t1_ := bef.Add(time.Duration(now.Sub(bef).Milliseconds()%86400000) * time.Millisecond)
	day = int(now.Sub(bef).Hours() / 24)
	// 计算在t1+两个时间的余数之后天数是否有变化
	if t1_.Day() != bef.Day() {
		day += 1
	}

	if swap {
		day = -day
	}

	return day
}
